---
import Date from '@/components/Date.astro'
import LinkToAddCalendar from '@/components/LinkToAddCalendar.astro'
import SectionTitle from '@/components/SectionTitle.astro'

interface Props {
  timestamp: number
}

const { timestamp } = Astro.props
const textResponsiveStyles = 'text-6xl font-bold md:text-7xl lg:text-8xl'
---

<section class="flex w-full flex-col place-items-center px-2 py-48" aria-label="cuenta atrás">
  <SectionTitle title="Cuenta atrás para el evento..." />

  <div
    class="flex select-none flex-col items-center justify-center gap-2 text-[var(--color-white)] sm:flex-row"
    id="countdown-big"
    data-date={timestamp}
    role="timer"
  >
    <div class="flex w-[240px] items-center justify-center gap-2 sm:w-auto">
      <Date
        dateType="DÍAS"
        attribute={{ 'data-days': '' }}
        className={textResponsiveStyles}
        wrapperClassName="my-0"
        max={129}
        withBackground={true}
      />

      <Date
        wrapperClassName="my-0"
        dateType="HORAS"
        attribute={{ 'data-hours': '' }}
        className={textResponsiveStyles}
        max={23}
        withBackground={true}
      />
    </div>

    <div class="flex w-[240px] items-center justify-center gap-2 sm:w-auto">
      <Date
        wrapperClassName="my-0"
        dateType="MINUTOS"
        attribute={{ 'data-minutes': '' }}
        className={textResponsiveStyles}
        max={59}
        withBackground={true}
      />

      <Date
        wrapperClassName="my-0"
        dateType="SEGUNDOS"
        attribute={{ 'data-seconds': '' }}
        className={textResponsiveStyles}
        max={59}
        withBackground={true}
      />
    </div>
  </div>
  <LinkToAddCalendar class="mt-6 text-center md:mt-8 lg:mt-10">
    Añade el evento al calendario!
  </LinkToAddCalendar>
</section>

<style is:global>
  .top-flip,
  .bottom-flip {
    position: absolute;
    width: 100%;
    overflow: hidden;
    display: flex;
    justify-content: center;
  }
  .top-flip {
    animation: flip-top 250ms ease-in;
  }

  .bottom-flip {
    animation: flip-bottom 250ms ease-out 250ms;
    transform: rotateX(90deg);
    bottom: 0;
  }

  @keyframes flip-top {
    100% {
      transform: rotateX(90deg);
    }
  }

  @keyframes flip-bottom {
    100% {
      transform: rotateX(0deg);
    }
  }
</style>

<script>
  import createCountdown, { type TimeParts } from '@/lib/countdown'
  import { $ } from '@/lib/dom-selector'

  function initCountdown() {
    const $countdown = $('#countdown-big')
    if (!$countdown) return

    const $days = {
      firstDigit: $('[data-days] [data-first-group]', $countdown),
      secondDigit: $('[data-days] [data-second-group]', $countdown),
      thirdDigit: $('[data-days] [data-third-group]', $countdown),
    }
    const $hours = {
      firstDigit: $('[data-hours] [data-first-group]', $countdown),
      secondDigit: $('[data-hours] [data-second-group]', $countdown),
    }
    const $minutes = {
      firstDigit: $('[data-minutes] [data-first-group]', $countdown),
      secondDigit: $('[data-minutes] [data-second-group]', $countdown),
    }
    const $seconds = {
      firstDigit: $('[data-seconds] [data-first-group]', $countdown),
      secondDigit: $('[data-seconds] [data-second-group]', $countdown),
    }
    const timestamp = Number($countdown?.getAttribute('data-date') ?? 0)
    const countdown = createCountdown(timestamp, {
      onTick({ days, hours, minutes, seconds }: TimeParts) {
        if (
          $days.firstDigit instanceof HTMLElement &&
          $days.secondDigit instanceof HTMLElement &&
          $days.thirdDigit instanceof HTMLElement
        ) {
          switch (days.length) {
            case 3:
              animateDigit($days.firstDigit, parseInt(days[0]))
              animateDigit($days.secondDigit, parseInt(days[1]))
              animateDigit($days.thirdDigit, parseInt(days[2]))
              break
            case 2:
              $days.firstDigit.parentNode?.removeChild($days.firstDigit)
              animateDigit($days.secondDigit, parseInt(days[0]))
              animateDigit($days.thirdDigit, parseInt(days[1]))
              break
            default:
              $days.secondDigit.parentNode?.removeChild($days.secondDigit)
              animateDigit($days.thirdDigit, parseInt(days[0]))
          }
        }

        if ($hours.firstDigit instanceof HTMLElement && $hours.secondDigit instanceof HTMLElement) {
          animateDigit($hours.firstDigit, parseInt(hours[0]))
          animateDigit($hours.secondDigit, parseInt(hours[1]))
        }

        if (
          $minutes.firstDigit instanceof HTMLElement &&
          $minutes.secondDigit instanceof HTMLElement
        ) {
          animateDigit($minutes.firstDigit, parseInt(minutes[0]))
          animateDigit($minutes.secondDigit, parseInt(minutes[1]))
        }

        if (
          $seconds.firstDigit instanceof HTMLElement &&
          $seconds.secondDigit instanceof HTMLElement
        ) {
          animateDigit($seconds.firstDigit, parseInt(seconds[0]))
          animateDigit($seconds.secondDigit, parseInt(seconds[1]))
        }
      },

      onComplete() {
        $('.countdown-text')?.remove()

        if (!$countdown) return

        $countdown.innerHTML = `¡El evento de presentación ha empezado! <span class='[text-shadow:none]'>🎉</span>
						<div class="flex w-full items-center justify-center w-full">
								<a
									href="https://www.twitch.tv/ibai"
									target="_blank"
									class="text-white text-stroke-dark mt-4 hover:scale-105 transition inline-flex cursor-pointer text-center text-base leading-tight font-normal md:text-xl"
								>
									<span class="text-center text-base leading-tight font-normal md:text-xl">
										TWITCH.TV/<span class="font-bold">IBAI</span>
									</span>
								</a>
							</div>
					`
        $countdown.className =
          'text-[var(--color-white)] font-semibold animate-fade-in text-lg sm:text-xl md:text-2xl text-center p-4 text-stroke-dark'
      },
    })

    return countdown
  }

  function animateDigit(flipCard: HTMLElement, newNumber: number) {
    const topHalf = flipCard.querySelector('.top') as HTMLElement
    const startNumber = parseInt(topHalf.textContent || '')
    if (newNumber === startNumber) return

    const bottomHalf = flipCard.querySelector('.bottom') as HTMLElement
    const topFlip = document.createElement('div')
    const bottomFlip = document.createElement('div')
    topFlip.classList.add(
      ...'top-flip h-[.5em] leading-none origin-bottom bg-theme-raisin-black border-b-2 border-b-theme-raisin-black'.split(
        ' ',
      ),
    )
    bottomFlip.classList.add(
      ...'bottom-flip h-[.5em] leading-none origin-top items-end bg-theme-raisin-black'.split(' '),
    )

    topHalf.textContent = `${startNumber}`
    bottomHalf.textContent = `${startNumber}`
    topFlip.textContent = `${startNumber}`
    bottomFlip.textContent = `${newNumber}`

    topFlip.addEventListener('animationstart', (e) => {
      topHalf.textContent = `${newNumber}`
    })
    topFlip.addEventListener('animationend', (e) => {
      topFlip.remove()
    })
    bottomFlip.addEventListener('animationend', (e) => {
      bottomHalf.textContent = `${newNumber}`
      bottomFlip.remove()
    })
    flipCard.append(topFlip, bottomFlip)
  }

  document.addEventListener('astro:page-load', () => {
    const countdown = initCountdown()
    countdown && countdown.start()
  })
</script>
